<?php
error_reporting(E_ALL);
include ("newmysqlSetUp.php");
define('EOL', (PHP_SAPI == 'cli') ? PHP_EOL : '<br/>');
define('DBCONF', "conference");
define('TBCONF', "conference_table");
define('DBLABA', "lab_achievement");
define('TBLABJ', "lab_achievement_journal");
define('TBLABJE', "lab_achievement_journal_extral");
define('TBLABC', "lab_achievement_conference");
define('TBLABCE', "lab_achievement_conference_extral");
define('TBIDEN', "paper_identify");
define('TBJNAL',"journal");
date_default_timezone_set('Asia/Shanghai');

$link = LinkMysql();

function sqlFilter($str)
{
	global $link;
	trim($str);
	return $link->real_escape_string($str);
}

// 获取发表时间
function getTime()
{
    extract($_POST);
	/**test
	$time="s t";
	$time_begin="2015-3-30";
	$time_end="2015-3-31";
	**/
    if (! empty($time)) {
        $condition = "1";
        switch ($time) {
            case "all":
                $condition = " 1 ";
                break;
            case "current":
                $condition .= "(发表时间   = '" . date("Y-m-d") . "')";
                break;
            case "set":
                $condition .= "(发表时间 >= '$time_begin' AND 发表时间 <= '$time_end')";
                break;
            default:
                // for debugging    
                echo "Not a legal date" . EOL;
                break;
        }
        return $condition;
    } else {
        return "1";
    }
}

// 获取领域 @par: area[、、、、]
function getArea()
{
	/*test
	$_POST['area']=array('net','computer');
	*/
    if (!empty($_POST['area'])) {
        $condition = "";
        foreach ($_POST['area'] as $value) {
            if (! empty($condition)) {
                $condition .= " OR ";
            }
			else{
				$condition .="(";
			}
            $condition .= "领域 LIKE '%".$value . "%' ";
        }
		$condition.=")";
		return $condition;
    } else {
        return "1";
    }
}

// 获取原文语言 @par: paperlanguage[en,ch,all]
function getLanguage()
{
	/*test
	$_POST['paperlanguage']='中文';
	*/
    if (empty($_POST['paperlanguage']) || $_POST['paperlanguage'] == 'all') {
        return "1";
    } else {
		$_POST['paperlanguage']=sqlFilter($_POST['paperlanguage']);
        return "(原文语言 = '" . $_POST['paperlanguage'] . "')";
    }
}

// 获取CCF等级 @par：CCFLevel
function getCCFLevel()
{
	/*TEST
	$_POST['CCFLevel']=array('A','B','C');
	*/
    if (empty($_POST['CCFLevel']) || $_POST['CCFLevel'][0] == "all") {
        return "1";
    } 
	else {    
		// Getting conference names
		// change : name level
		global $link;
		$sql = "";
		foreach ($_POST['CCFLevel'] as $val) {
			$sql .= empty($sql)?"select name from " . TBCONF . " where ":" OR ";
			$sql .= " level = '$val' ";
		}
		//delete
		echo "CFSQ:".$sql.EOL;
		$ret = MysqlQuery($link, DBCONF, $sql);
		if(!$ret){
			//for debuging
			echo "At line:".__LINE__.".Query failed:".$link->error.EOL;
			return "";
		}
		$condition = "";
		while ($row = $ret->fetch_assoc()) {
			$condition .= empty($condition)?"(":" OR ";
			$condition .= " 会议名 LIKE '%" . $row['name'] . "%' ";
		}
		$condition .= ")";
		return $condition;
    }
}
// 获取影响因子 @infection[all ,1,2,3]
// 影响因子与ccf等级之间的关系【&&或者||】有待考察
function getInfection()
{
	/*TEST
	$_POST['infection']=array('1','3');
	*/

    if (empty($_POST['infection']) || $_POST['infection'][0] == "all") {
        return "1";
    }
	else {
        // Getting conference names
        // change : name infection
        global $link;
        $sql = "";
        foreach ($_POST['infection'] as $val) {
			$val=intval($val);
            $infbegin=($val-1)*0.5;
			$infend=($val==3)?99999:$val*0.5;
			$sql .= empty($sql)?"select name from " . TBCONF . " where" : " OR "; 
			$sql .= " (infection >=$infbegin && infection <= $infend)";
        }
		//delete
		//echo "sql:".$sql.EOL;
        $ret = MysqlQuery($link, DBCONF, $sql);
		if(!$ret){
			//for debuging
			echo "At line:".__LINE__.".Query failed:".$link->error.EOL;
			return "";
		}
        $condition = "";
        while ($row = $ret->fetch_assoc()) {
			$condition .= empty($condition)?"(":" OR ";
            $condition .= " 会议名 LIKE '%" . $row['name']."%'";
        }
        $condition .= ")";
        return $condition;
    }
}

/******************
 * JnalLevel[1,2,3,4,all]
 * 
 * 
 * 
 * 
 * */

function getJnalLevel()
{
    global $link;
	/*test
	$_POST['JnalLevel']=array('1','2','3','4');
	*/
    if(empty($_POST['JnalLevel']) || $_POST['JnalLevel']=="all"){
        return "1";
    }
    $sql="";
    foreach($_POST['JnalLevel'] as $val)
    {
		$sql.=empty($sql)?"select name from ".TBJNAL." WHERE ":" OR ";
        $sql.=" area = ".$val;
    }
    //delete NEXT SENTENCE
	//echo "CONFSQL:".$sql.EOL;
    $ret=MysqlQuery($link,DBCONF,$sql);
    if(!$ret){
        //for debuging
        echo "At line:".__LINE__.".Query failed:".$link->error.EOL;
    }
    else{
        $condition="";
        while($row=$ret->fetch_assoc())
        {
			$condition.=empty($condition)?"(":" OR ";
            $condition.="刊名 LIKE '%".$row['name']."%'";
        }
		$condition.=")";
        return $condition;        
    }
}

// 获取论文类型 @par papertype[pub,rem,all]
// 搜索函数需要根据返回值进行处理
function getPaperType()
{
    if (empty($_POST['papertype']) || $_POST['papertype'] == "all") {
        return "1";
    } else {
        return $_POST['papertype'];
    }
}

// 获取基本信息检索选项
// @par
//        key1 value1
// logic2 key2 value2
// .......
function getKeyWords()
{
    $key_number = 10; // 可检索选项
	//TEST
	$_POST=array("key1"=>"冯军","value1"=>"第一作者","logic2"=>"or","key2"=>"ywj","value2"=>"第二作者");
    extract($_POST);
    $condition = "";
    $i = 1;
    while ($i <= $key_number) {
        $key = "key" . $i;
        $value = "value" . $i;
        $logic = "logic" . $i;
        $i += 1;
        if (empty($$value)) {
            continue;
        }
        $$key=sqlFilter($$key);
		$$value=sqlFilter($$value);
		$condition .= empty($condition)?"(":" ".$$logic." ";
		$condition .= $$value." LIKE '%".$$key."%' ";
    }
	if(!empty($condition))
	$condition .=")";
    return $condition;
}
//获取基本的检索信息：关键字。时间。领域。语言。论文类型
function getBaseConditions()
{
    $conditions = getKeyWords();
    if (empty($_POST) || empty($conditions)) {
        return false;
    }
    $conditions .= " AND " . getTime() . " AND " . getArea() . " AND " . getLanguage();
	return $conditions;
}

//获取一条会议或者期刊记录 
//@$type  identify the j or c
//@$rec   a base info of a records
//return the detail information of a paper
function getOneRec($rec,$type)
{
    global $link;
    $answer=array();
    foreach($rec as $key=>$val)
    {
        $answer[$key]=$val;
    }
    $table=($type=="C")?TBLABCE:TBLABJE;
	$sql="select item,content from ".$table." WHERE 标题 LIKE '%".$rec['标题']."%' AND 第一作者 LIKE '%".$rec['第一作者']."%';";
	//delete NEXT SENTENCE
	//echo "extra sql:".$sql.EOL;
    $extra=MysqlQuery($link, DBLABA, $sql);
    if($extra){
        while($row=$extra->fetch_assoc())
        {
            $answer[$row['item']]=$row['content'];//add extra information
        }
    }
    else{
        //for debuging
        echo "At line:".__LINE__.".Query failed:".$link->error.EOL;
    }

    return $answer;
}
//显示一篇论文
//cont：array include the info of a paper
function getHtmlContent($cont,$type,&$content)
{

	//delete
	echo "Record:<pre><font color='red'>";
	var_dump($cont);
	echo "</font></pre>".EOL;
    
}

/*
//获取数据库里面所有满足检索条件的期刊或者会议论文
function getJnalConf($sql,$type,&$content)
{
    global $link;
    $count=0;
    $ret=MysqlQuery($link,DBLABA,$sql);
    if(!$ret){
        //for debuging
        echo "At line:".__LINE__.".Query failed:".$link->error.EOL;
		return 0;
    }
    while($row=$ret->fetch_assoc())
    {
        $count+=1;
        $detailinfo=getOneRec($row,$type);
        getHtmlContent($detailinfo,$type,$content);
    }
    return $count;
}

//搜索期刊或者会议   return count
function searchMysql()
{
    $base=getBaseConditions();
    if ($base) {
      $content="";
      $cond=" where $base ";
      $sql="SELECT * FROM ".TBLABJ.$cond." AND ".getJnalLevel().";";
      //for debuging
      echo "You searched for:<font color='red'>".$sql."</font>".EOL;
      $jcount=getJnalConf($sql,"J",$content);
      $sql="SELECT * FROM ".TBLABC.$cond." AND ".getCCFLevel()." AND ".getInfection();
      //for debuging
      echo "You searched for:<font color='red'>".$sql."</font>".EOL;
      $ccount=getJnalConf($sql,"C",$content);
      echo "Total records:".($jcount+$ccount).EOL;
      echo $content;
    }
    else{
        //for debuging
        echo "invalid searching choices".EOL;   
    }
}      
	searchMysql();
	
*/

//获取数据库里面所有满足检索条件的期刊或者会议论文
function getJnalConf($sql,&$content)
{
    global $link;
    $count=0;
    $ret=MysqlQuery($link,DBLABA,$sql);
    if(!$ret){
        //for debuging
        echo "At line:".__LINE__.".Query failed:".$link->error.EOL;
		return 0;
    }
    while($row=$ret->fetch_assoc())
    {
        $count+=1;
		if(!empty($row['卷']) && $row['卷']=="conf"){
			$type="C";
		}
		else{
			$type="J";
		}
        $detailinfo=getOneRec($row,$type);
        getHtmlContent($detailinfo,$type,$content);
    }
    return $count;
}

//搜索期刊或者会议并且排序   return count
//usage：searchMysql("ORDER BY 发表时间 ASC");
function searchMysql($order)
{
    $base=getBaseConditions();
    if ($base) {
      $content="";
      $cond=" where $base ";
      $sql1="(SELECT *,'conf' AS 卷,null AS 期,null AS 页码 FROM ".TBLABC.$cond." AND ".getCCFLevel()." AND ".getInfection().") ";
      $sql2="(SELECT * FROM ".TBLABJ.$cond." AND ".getJnalLevel().")";
	  if(empty($order)){
		$sql=$sql1." UNION ".$sql2;
	  }
	  else if($order=="J"){
		$sql=$sql2." UNION ".$sql1;
	  }
	  else{
		$sql=$sql1." UNION ".$sql2." ".$order;
	  }
	  //for debuging
      echo "You searched for:<font color='red'>".$sql."</font>".EOL;
      $count=getJnalConf($sql,$content);
      echo "Total records:".($count).EOL;
      echo $content;
    }
    else{
        //for debuging
        echo "invalid searching choices".EOL;   
    }
}     
//@par order type
//order[1,2,3,4,5,6]
//标题[A-Z]、标题[Z-A],最新发表在前、较晚发表在前、被引次数增、被引次数减，会议在前、期刊在前

function disOnWeb()
{
	$order="";
	/*test
	$_POST['order']=8;
	*/
	if(!empty($_POST['order'])){
		$order="ORDER BY ";
		$_POST['order']=sqlFilter($_POST['order']);
		switch($_POST['order'])
		{
			case '1':
				$order .= " 标题 ASC";
			break;
			case '2':
				$order .= " 标题 DESC";
			break;
			case '3':
				$order .= " 发表时间 DESC";
			break;
			case '4':
				$order .= " 发表时间 ASC";
			break;
			case '5':
				$order .= " 被引次数 ASC";
			break;
			case '6':
				$order .= " 被引次数 DESC";
			break;
			case '7':
				$order = "";
			break;
			case '8':
				$order = "J";
			break;
			default:
				$order="";
			break;
		}
	}

	searchMysql($order);
}

	disOnWeb();
?>
